﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;

namespace Web.Function
{
    /// <summary>
    /// 动态获取脚本或样式表类
    /// </summary>
    public class FileList
    {
        private string filePath;

        public FileList(string path)
        {
            if (path[path.Length - 1] != '\\')
                filePath = path + "\\";
            else
                filePath = path;
        }

        /// <summary>
        /// 获取脚本列表
        /// </summary>
        /// <param name="path">文件夹相对路径</param>
        /// <param name="remover">移除的项</param>
        /// <returns>脚本列表</returns>
        public string GetJsList(string path, params string[] remover)
        {
            if (path[path.Length - 1] != '/')
                path += "/";
            List<string> array = new List<string>();
            getFileList(array, filePath + path, path, ".js", remover);
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < array.Count; ++i)
            {
                result.Append("    <script type=\"text/javascript\" src=\"");
                result.Append(array[i]);
                result.Append("\"></script>\n");
            }
            return result.ToString();
        }

        /// <summary>
        /// 获取样式列表
        /// </summary>
        /// <param name="path">文件夹相对路径</param>
        /// <param name="remover">移除的项</param>
        /// <returns>样式列表</returns>
        public string GetCssList(string path, params string[] remover)
        {
            if (path[path.Length - 1] != '/')
                path += "/";
            List<string> array = new List<string>();
            getFileList(array, filePath + path, path, ".css", remover);
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < array.Count; ++i)
            {
                result.Append("    <link rel=\"stylesheet\" type=\"text/css\" href=\"");
                result.Append(array[i]);
                result.Append("\"/>\n");
            }
            return result.ToString();
        }

        private static void getFileList(List<string> result, string path, string relaPath, string filter, string[] remover)
        {
            if (!Directory.Exists(path)) return;
            DirectoryInfo dir = new DirectoryInfo(path);
            foreach (FileInfo file in dir.GetFiles())
            {
                if (file.Extension.ToLower() == filter.ToLower())
                {
                    foreach (string rm in remover)
                        if (file.Name.ToLower() == rm.ToLower())
                            goto next;
                    result.Add(relaPath + file.Name);
                }
            next: ;
            }
            foreach (DirectoryInfo sub in dir.GetDirectories())
            {
                getFileList(result, sub.FullName, relaPath + sub.Name + "/", filter, remover);
            }
        }
    }
}